package com.binvshe.binvshe.organization;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.message.dao.MessageHelper;
import com.binvshe.binvshe.mine.usercenter.UserCenterActivity;
import com.daimajia.swipe.SwipeLayout;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.PullableListActivity;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class ClubMemberActivity extends PullableListActivity {

    private int mPage = 0;
    private static final String KEY_CLUB_ID = "key_club_id";
    private static final String KEY_LEADER_ID = "key_leader_id";

    @InjectExtra(KEY_CLUB_ID)
    int mClubId;
    @InjectExtra(KEY_LEADER_ID)
    int mLeaderId;

    public static void start(Context context, int clubId, int leaderId) {
        Intent starter = new Intent(context, ClubMemberActivity.class);
        starter.putExtra(KEY_CLUB_ID, clubId);
        starter.putExtra(KEY_LEADER_ID, leaderId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Dart.inject(this);
        enableBackButton();
        getCustomToolbar().setTitle("成员列表");
        startLoading();
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new MemberAdapter(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPage = 0;
        startLoading();
    }

    private ListDataRequestListener<Account> mResponceListener = new ListDataRequestListener<>(this, Account.class, true);

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        mPage = 0;
        getData().clear();
        startLoading();
    }

    void getMemberListData() {
        if (mPage == 0 || mResponceListener.getResponseDataParser().hasMore()) {
            mPage++;
            MyHttpRequest request = new MyHttpRequest(this);
            String url = String.format(UrlCenter.CLUB_MEMBER, mClubId);
            UrlParams urlParams = new UrlParams();
            urlParams.put(ParamKey.PAGE, mPage + "");
            urlParams.put(ParamKey.SIZE, 8 + "");
            request.get(url, urlParams, mResponceListener);
        }
    }

    @Override
    public void onStartLoading() {
        getMemberListData();
    }

    private void sendRequestDeletMember(int memberId) {
        MyHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.DELETE_MEMBER, mClubId, memberId);
        UrlParams urlParams = new UrlParams();
        request.delete(url, urlParams, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                EasyToast.showToast(ClubMemberActivity.this, "删除成功");
                getAdapter().notifyDataSetChanged();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(ClubMemberActivity.this, strMsg);
            }
        });
    }

    public class MemberAdapter extends RecyclerViewBaseAdapter<Account> {


        public MemberAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_member_list));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final Account member = getData().get(position);
            if (!TextUtils.isEmpty(member.getPortrait()))
                IML.load(getContext(), viewHolder.mImgHead, member.getPortrait());

            if (!TextUtils.isEmpty(member.getNickName()))
                viewHolder.mTvName.setText(member.getNickName());

            if (AccountManager.getCurrentAccount() != null) {
                if (Integer.parseInt(AccountManager.getCurrentAccount().getUserId()) != mLeaderId) {
                    setViewForMember(viewHolder);
                } else {

                    if (Integer.parseInt(AccountManager.getCurrentAccount().getUserId()) == Integer.parseInt(member.getUserId())){
                        viewHolder.swlytSwip.setSwipeEnabled(false);
                    }
                    viewHolder.swlytSwip.setSwipeEnabled(true);
                    viewHolder.mTvCheckDays.setVisibility(View.GONE);
                    viewHolder.mTvCheckDays.setText("连续签到" + member.getCheckInDays() + "天");
                    viewHolder.btnDelete.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            sendRequestDeletMember(Integer.parseInt(member.getUserId()));
                        }
                    });
                }
            } else {
                setViewForMember(viewHolder);
            }

            if (member.getClubRole() == 0) {
                viewHolder.mTvRole.setText("成员");
                viewHolder.swlytSwip.setSwipeEnabled(true);
                viewHolder.mTvCheckDays.setVisibility(View.GONE);

            } else {
                viewHolder.mTvRole.setText("管理员");
                viewHolder.swlytSwip.setSwipeEnabled(false);
            }

            viewHolder.mImgHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserCenterActivity.start(getContext(), member.getUserId());
                }
            });

        }

        private void setViewForMember(VH viewHolder) {
            viewHolder.swlytSwip.setSwipeEnabled(false);
            viewHolder.mTvCheckDays.setVisibility(View.GONE);
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.btnDelete)
            Button btnDelete;
            @Bind(R.id.mImgHead)
            CircleImageView mImgHead;
            @Bind(R.id.mTvName)
            TextView mTvName;
            @Bind(R.id.mTvCheckDays)
            TextView mTvCheckDays;
            @Bind(R.id.mTvRole)
            TextView mTvRole;
            @Bind(R.id.swlytSwip)
            SwipeLayout swlytSwip;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
